from django.contrib import auth
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserCreationForm
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.views import View


@login_required
def logout(request):
    auth.logout(request)
    return redirect('learning_logs:index')


class LoginView(View):

    @staticmethod
    def get(request):
        return render(request, 'users/login.html')

    @staticmethod
    def post(request):
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = auth.authenticate(username=username, password=password)
        if user and user.is_active:
            auth.login(request, user)
            return JsonResponse({'code': 0, 'msg': 'success'})

        return JsonResponse({'code': 1, 'msg': 'failed'})


class RegisterView(View):

    @staticmethod
    def get(request):
        return render(request, 'users/register.html')

    @staticmethod
    def post(request):
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            auth.login(request, user)
            return JsonResponse({'code': 0, 'msg': 'success'})

        return JsonResponse({'code': 1, 'msg': 'failed'})
